import "./index.less";
import { View, Text, ScrollView } from "@tarojs/components";
import { useState } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import { TPlanMotion } from "@/types";
import { getPlan, addRecords } from "@/request";
import MotionIcon from "@/components/Icons/MotionIcon";
import Timing from "./Timing";
import { getOptionTxt, getSecondsFormat } from "@/utils";
import { SetsTypeOptions, UnitOptions } from "@/utils/options";
import SetCell from "./SetCell";
import MotionCard from "./MotionCard";
import TimeIcon from "@/components/Icons/TimeIcon";
import CheckLineIcon from "@/components/Icons/CheckLineIcon";
import { TimeFillIcon } from "@/components/Icons";
import { PopupProvider, usePopup } from "@/store/popup";

type TemplateMotion = TPlanMotion & {
  takeTime: number;
  done: boolean;
  doneSets: boolean[];
  show: boolean;
};

const CustomTime = ({ onConfirm, value }) => {
  const { openPopup } = usePopup();
  return (
    <View
      className="box-button"
      onClick={(e) => {
        e.stopPropagation();
        openPopup({
          type: "number",
          showConfirm: false,
          props: {
            label: "训练时间",
            initValue: value,
            unitOptions: [
              { label: "秒", value: 1 },
              { label: "分", value: 60 },
            ],
          },
          onConfirm,
        });
      }}
    >
      自定义时长
    </View>
  );
};

const StartPlan = () => {
  const [popup, setPopup] = useState({
    open: false,
    label: "",
    value: 0,
    index: 0,
  });

  const id = Taro.getCurrentInstance().router?.params?.id;
  const [time, setTime] = useState({
    open: false,
    title: "",
    index: 0,
    direction: "up",
    initialSeconds: 0,
    setIndex: 0,
  });

  const [data, setData] = useState<Array<TemplateMotion>>([]);
  const [planName, setPlanName] = useState<string>();
  useDidShow(() => {
    if (id) {
      handleGetData(id);
    }
    Taro.setNavigationBarTitle({
      title: "执行计划",
    });
  });

  const handleChangeStatus = (itemIndex: number, setIndex: number) => {
    const newData = [...data];
    newData[itemIndex].doneSets[setIndex] =
      !newData[itemIndex].doneSets[setIndex];
    newData[itemIndex].done = newData[itemIndex].doneSets.every((item) => item);

    setData(newData);
  };

  const handleTimeDown = (itemIndex: number, setIndex: number) => {
    setTime({
      ...time,
      title: data[itemIndex].name,
      open: true,
      index: itemIndex,
      direction: "down",
      initialSeconds: data[itemIndex].sets[setIndex][1],
      setIndex,
    });
  };

  const handleChange = (name, i, value?) => {
    const newData = [...data];

    switch (name) {
      case "toggleShow":
        newData[i].show = !newData[i].show;
        break;
      case "time":
      case "edittime":
        newData[i].takeTime = value;
        if (value !== 0) {
          newData[i].done = true;
        }
        break;
      default:
        break;
    }

    setData(newData);
  };

  const handleGetData = async (id: string) => {
    const res = await getPlan(id);

    setData(
      res.motions.map((item) => ({
        ...item,
        takeTime: 0,
        done: false,
        doneSets: item.sets.map(() => false),
        show: true,
      }))
    );
    setPlanName(res.name);
  };

  const handleTime = (name, i, initialSeconds) => {
    setTime({
      ...time,
      title: name,
      open: true,
      index: i,
      initialSeconds,
      direction: "up",
    });
  };
  const handleCloseTime = () => {
    setTime({
      ...time,
      open: false,
    });
  };

  const handleSubmit = async () => {
    const records: any[] = [];
    data.forEach((item, index) => {
      if (item.recordWay === 0) {
        const haveDone = item.doneSets.some((item) => item);
        if (haveDone) {
          records.push({
            motionId: item.motionId,
            sets: item.sets.filter((it, i) => item.doneSets[i]),
            recordWay: item.recordWay,
            takeTime: 0,
            unit: item.unit,
            setsType: item.setsType,
          });
        }
      } else {
        if (item.takeTime !== 0) {
          records.push({
            motionId: item.motionId,
            recordWay: item.recordWay,
            takeTime: item.takeTime,
          });
        }
      }
    });

    await addRecords({
      records,
    }).then(() => {
      Taro.switchTab({
        url: `/pages/record/record`,
      });
    });
  };

  return (
    <PopupProvider>
      <View className="start-plan">
        <View className="page-header">
          <View className="flex-align">
            <Text style={{ marginRight: Taro.pxTransform(12) }}>
              {planName}
            </Text>
          </View>
          <View className="page-header-right">
            <MotionIcon />
            <View style={{ marginLeft: Taro.pxTransform(12) }}>
              <Text>{data?.filter((item) => item.done).length}</Text>
              <Text>/</Text>
              <Text>{data?.length}</Text>
            </View>
          </View>
        </View>
        <ScrollView className="start-plan-scroll" scrollY>
          <View className="start-plan-scroll-inner">
            {data?.map((item, i) => {
              const unit = getOptionTxt(item.unit, UnitOptions);
              const setType = getOptionTxt(item.setsType, SetsTypeOptions);

              if (item.recordWay === 0) {
                return (
                  <MotionCard
                    key={item.uuid}
                    motion={item}
                    className={item.done ? "finished" : ""}
                    onClick={() => handleChange("toggleShow", i)}
                  >
                    {item.show && (
                      <View className="start-plan-item-sets">
                        {item.sets?.map((set, index) => {
                          return (
                            <SetCell
                              unit={unit}
                              setType={setType}
                              index={index}
                              isDone={item.doneSets[index]}
                              set={set}
                              onLongPress={() => {
                                if (item.setsType === 0) return;
                                handleChangeStatus(i, index);
                              }}
                              onClick={(e) => {
                                e.stopPropagation();
                                // 组次
                                if (item.setsType === 0) {
                                  handleChangeStatus(i, index);
                                } else {
                                  // 组秒
                                  if (item.doneSets[index]) {
                                    handleChangeStatus(i, index);
                                  } else {
                                    handleTimeDown(i, index);
                                  }
                                }
                              }}
                            />
                          );
                        })}
                      </View>
                    )}
                    <View
                      style={{ textAlign: "right" }}
                      className="record-result"
                    >
                      <Text>
                        {item.doneSets?.filter((item) => item).length}
                      </Text>
                      <Text>/</Text>
                      <Text>{item.sets?.length}</Text>
                    </View>
                  </MotionCard>
                );
              }

              return (
                <MotionCard
                  key={item.uuid}
                  motion={item}
                  className={item.takeTime !== 0 ? "finished" : ""}
                >
                  <View className="flex-end">
                    {item.takeTime !== 0 ? (
                      <TimeFillIcon type="primary" size={1} />
                    ) : (
                      <TimeIcon size={1} type="default" />
                    )}

                    <View
                      style={{ marginLeft: Taro.pxTransform(12) }}
                      className="record-result"
                    >
                      {getSecondsFormat(item.takeTime)}
                    </View>
                  </View>
                  <View className="flex-end">
                    <View
                      className="box-button"
                      onClick={() => {
                        handleTime(item.name, i, item.takeTime);
                      }}
                    >
                      计时
                    </View>
                    <CustomTime
                      value={String(item.takeTime)}
                      onConfirm={(v) => {
                        console.log(v);
                        handleChange("edittime", i, v);
                      }}
                    />
                  </View>
                </MotionCard>
              );
            })}
          </View>
        </ScrollView>
      </View>

      {time.open && time.direction === "up" && (
        <Timing.Up
          title={time.title}
          initialSeconds={time.initialSeconds}
          onClose={handleCloseTime}
          onDone={(s) => {
            handleCloseTime();
            handleChange("time", time.index, s);
          }}
        />
      )}
      {time.open && time.direction === "down" && (
        <Timing.Down
          title={time.title}
          initialSeconds={time.initialSeconds}
          onClose={handleCloseTime}
          onDone={() => {
            handleCloseTime();
            handleChangeStatus(time.index, time.setIndex);
          }}
        />
      )}

      {/* <PageContainer show={popup.open} key={String(popup.value)}>
        <NumberEditor
          label={popup.label}
          unitOptions={[
            { label: "秒", value: 1 },
            { label: "分钟", value: 60 },
          ]}
          initValue={String(popup.value)}
          onConfirm={(v) => {
            handleChange("edittime", popup.index, v);
            setPopup({ ...popup, open: false });
          }}
        />
      </PageContainer> */}

      <CheckLineIcon
        onClick={handleSubmit}
        type="white"
        size={1.6}
        circle="primary"
        circleSize={3.2}
        style={{
          position: "fixed",
          bottom: Taro.pxTransform(60),
          right: Taro.pxTransform(60),
        }}
      />
    </PopupProvider>
  );
};

export default StartPlan;
